"""
Verify that workspace_id is required for /api/v1/hiagent/personal-agents
Test cases:
1. Without workspace_id - should fail with 422 error
2. With workspace_id - should succeed
"""
import sys
import os

# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import requests
import json
from src.llm.hiagent_app.utils.api_client import HiAgentConfig

def test_personal_agents_without_workspace_id():
    """Test case 1: Call API without workspace_id should fail"""
    print("\n" + "="*60)
    print("TEST 1: Call /personal-agents WITHOUT workspace_id")
    print("="*60)

    url = "http://localhost:8000/api/v1/hiagent/personal-agents"

    # Call without workspace_id parameter
    params = {
        "page": 1,
        "page_size": 10
    }

    print(f"\nRequest: GET {url}")
    print(f"Params: {json.dumps(params, indent=2)}")

    try:
        response = requests.get(url, params=params)
        print(f"\nResponse Status: {response.status_code}")
        print(f"Response Body: {json.dumps(response.json(), indent=2, ensure_ascii=False)}")

        if response.status_code == 422:
            print("\n✓ PASS: API correctly rejects request without workspace_id")
            return True
        else:
            print("\n✗ FAIL: API should return 422 but got", response.status_code)
            return False

    except Exception as e:
        print(f"\n✗ FAIL: Exception occurred: {str(e)}")
        return False


def test_personal_agents_with_workspace_id():
    """Test case 2: Call API with workspace_id should succeed"""
    print("\n" + "="*60)
    print("TEST 2: Call /personal-agents WITH workspace_id")
    print("="*60)

    # Get workspace_id from config
    config = HiAgentConfig()
    workspace_id = config.DEFAULT_WORKSPACE_ID

    if not workspace_id:
        print("\n✗ FAIL: DEFAULT_WORKSPACE_ID not configured")
        return False

    url = "http://localhost:8000/api/v1/hiagent/personal-agents"

    params = {
        "workspace_id": workspace_id,
        "page": 1,
        "page_size": 10
    }

    print(f"\nRequest: GET {url}")
    print(f"Params: {json.dumps(params, indent=2, ensure_ascii=False)}")

    try:
        response = requests.get(url, params=params)
        print(f"\nResponse Status: {response.status_code}")

        if response.status_code == 200:
            data = response.json()
            print(f"Response Body: {json.dumps(data, indent=2, ensure_ascii=False)}")

            if data.get("success"):
                agents = data.get("data", {}).get("items", [])
                total = data.get("data", {}).get("total", 0)
                print(f"\n✓ PASS: Got {len(agents)} agents, total: {total}")
                return True
            else:
                print(f"\n✗ FAIL: Response success=False")
                return False
        else:
            print(f"Response Body: {json.dumps(response.json(), indent=2, ensure_ascii=False)}")
            print(f"\n✗ FAIL: Expected 200 but got {response.status_code}")
            return False

    except Exception as e:
        print(f"\n✗ FAIL: Exception occurred: {str(e)}")
        import traceback
        traceback.print_exc()
        return False


def test_service_layer():
    """Test case 3: Test service layer validation"""
    print("\n" + "="*60)
    print("TEST 3: Test service layer validation")
    print("="*60)

    try:
        from src.llm.hiagent_app.services.personal_agent_service import PersonalAgentService
        from src.llm.hiagent_app.models.hiagent_models import ListOption

        service = PersonalAgentService()
        list_opt = ListOption(page=1, page_size=10)

        # Try to call without workspace_id
        print("\nCalling list_personal_agents with workspace_id=None...")

        try:
            agents, total = service.list_personal_agents(
                list_opt=list_opt,
                filter_opt=None,
                workspace_id=None
            )
            print("\n✗ FAIL: Service should raise ValueError but didn't")
            return False
        except ValueError as e:
            print(f"\nCaught expected ValueError: {str(e)}")
            if "workspace_id is required" in str(e):
                print("✓ PASS: Service correctly validates workspace_id")
                return True
            else:
                print("✗ FAIL: Wrong error message")
                return False

    except Exception as e:
        print(f"\n✗ FAIL: Exception occurred: {str(e)}")
        import traceback
        traceback.print_exc()
        return False


if __name__ == "__main__":
    print("\n" + "="*60)
    print("WORKSPACE_ID REQUIRED VERIFICATION")
    print("="*60)

    results = []

    # Test 1: API without workspace_id
    results.append(("API without workspace_id", test_personal_agents_without_workspace_id()))

    # Test 2: API with workspace_id
    results.append(("API with workspace_id", test_personal_agents_with_workspace_id()))

    # Test 3: Service layer validation
    results.append(("Service layer validation", test_service_layer()))

    # Summary
    print("\n" + "="*60)
    print("SUMMARY")
    print("="*60)

    passed = sum(1 for _, result in results if result)
    total = len(results)

    for name, result in results:
        status = "✓ PASS" if result else "✗ FAIL"
        print(f"{status}: {name}")

    print(f"\nTotal: {passed}/{total} tests passed")

    if passed == total:
        print("\n✓ All tests passed!")
        sys.exit(0)
    else:
        print("\n✗ Some tests failed!")
        sys.exit(1)
